package com.hys.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.dao.CoopAuditMapper;
import com.hys.dto.TaskNextDTO;
import com.hys.entity.CoopAudit;
import com.hys.entity.CoopInfo;
import com.hys.entity.Task;
import com.hys.enums.AuditStatusEnum;
import com.hys.enums.CoopStatusEnum;
import com.hys.exception.ServiceException;
import com.hys.service.CoopAuditService;
import com.hys.service.CoopInfoService;
import com.hys.service.TaskService;
import com.hys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 有优化空间：
 *      1. 把任务存在缓存中
 *      2. 减少查询次数
 *      3. 没有优化的原因是业务系统数据过少
 */
@Service
public class CoopAuditServiceImpl extends ServiceImpl<CoopAuditMapper, CoopAudit> implements CoopAuditService {

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;


    @Override
    public List<CoopAudit> list(Integer copperId, String batchNo) {
        QueryWrapper<CoopAudit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CoopAudit::getCoopId, copperId).eq(CoopAudit::getBatchNo,batchNo);
        return list(queryWrapper);
    }

    @Override
    public void audited(Integer id, Integer status) {

        CoopInfo coopInfo = coopInfoService.getById(id);
        if(coopInfo == null){
            throw new ServiceException("未查询到当前状态记录！");
        }
        if(CoopStatusEnum.REJECTED.getCode().equals(coopInfo.getStatus())){
            throw new ServiceException("当前资料已拒绝未修改，暂不能审核！");
        }
        if(CoopStatusEnum.PASSED.getCode().equals(coopInfo.getStatus())){
            throw new ServiceException("当前资料已经审核通过，请勿重复审核！");
        }
        // 查看要执行的任务
        Integer infoId = coopInfo.getId();
        String batchNo = coopInfo.getBatchNo();
        TaskNextDTO nextTask = getNextTask(infoId, batchNo, coopInfo.getTaskName());
        Task task = nextTask.getTask();
        batchNo = nextTask.getBatchNo();
        if(currentIsCanAudit(task) == false){
            throw new ServiceException("当前用户无权限审核此节点");
        }
        // 保存审批操作
        CoopAudit audit = new CoopAudit().setCoopId(id)
                .setOrderNumber(task.getOrderNum())
                .setTaskName(task.getName()).setBatchNo(batchNo)
                .setStatus(status).setCreateUser(userService.userInfo().getId())
                .setCreateTime(new Date());
        save(audit);
        // 变更主表状态
        if( AuditStatusEnum.REJECTED.getCode().equals(status) ){
            // 更新主表状态为被拒绝
            coopInfo.setStatus(CoopStatusEnum.REJECTED.getCode());
            coopInfo.setBatchNo(batchNo);
        }else{
            // 第一次变更状态为审批中
            if(taskService.isFirstTask(task)){
                coopInfo.setStatus(CoopStatusEnum.AUDITING.getCode());
                coopInfo.setBatchNo(batchNo);
            }
            // 最后一次变更状态为审批通过
            if(taskService.isLastTask(task)){
                coopInfo.setStatus(CoopStatusEnum.PASSED.getCode());
                coopInfo.setBatchNo(batchNo);
            }
        }
        coopInfoService.updateById(coopInfo);
    }

    @Override
    public Boolean getIsEnabledAudit(CoopInfo coopInfo) {

        TaskNextDTO nextTask = getNextTask(coopInfo.getId(), coopInfo.getBatchNo(), coopInfo.getTaskName());
        Task task = nextTask.getTask();
        return currentIsCanAudit(task);
    }

    /**
     * 当前用户是否
     * @param task
     * @return
     */
    private Boolean currentIsCanAudit(Task task) {

        String[] split = task.getCandidateUsers().split(",");
        String currentUserId = userService.userInfo().getId().toString();
        Optional<String> any = Arrays.stream(split).filter(userIdStr -> userIdStr.equals(currentUserId)).findAny();
        if(any.isPresent()){
            return true;
        }
        return false;
    }

    private TaskNextDTO getNextTask(Integer infoId, String batchNo, String taskName) {

        TaskNextDTO taskDTO = new TaskNextDTO();
        // 查询当前最大任务
        List<Task> lists = taskService.listTasksByName(taskName);
        // 没有则为任务一
        if(StrUtil.isEmpty(batchNo)){
            Task task = lists.get(0);
            taskDTO.setTask(task);
            taskDTO.setBatchNo(RandomUtil.randomString(10));
            return taskDTO;
        }
        // 存在则查询最大任务
        CoopAudit coopAudit = getAuditMax( infoId, batchNo );
        Task task = taskService.getTaskByNameNumber(taskName, coopAudit.getOrderNumber());
        Task nextTask = taskService.getNextTask(task);

        taskDTO.setTask(nextTask);
        taskDTO.setBatchNo(batchNo);

        return taskDTO;
    }

    private CoopAudit getAuditMax(Integer infoId, String batchNo) {

        QueryWrapper<CoopAudit> qw = new QueryWrapper<>();
        qw.lambda().eq(CoopAudit::getCoopId, infoId)
                .eq(CoopAudit::getBatchNo, batchNo)
                .last("limit 1").orderByDesc(CoopAudit::getOrderNumber);
        return getOne(qw);
    }


}
